package com.cl.short_video_java.util;

import com.cl.short_video_java.service.SysSettingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import java.util.List;
import java.util.UUID;

/**
 * @Author 付
 * @Date 2024-11-22 11:15
 * @Version 1.0
 * @description FTP 文件上传 云服务器
 * @since 1.0
 */
@Component
@Slf4j
public class FtpUtil {

	@Autowired
	private SysSettingService settingService;
	public String uploadFile(MultipartFile file) throws IOException {
		String serverIp = settingService.getSysSettingByKey("ftp_img_server_ip");
		String ftpUser = settingService.getSysSettingByKey("ftp_user");
		String ftpPass = settingService.getSysSettingByKey("ftp_pass");
		Integer ftpPort = Integer.valueOf(settingService.getSysSettingByKey("ftp_port"));
		FTPClient ftp = new FTPClient();
		String path = settingService.getSysSettingByKey("ftp_path");
		String url = "";
		try {
			//连接服务器
			int reply;
			ftp.connect(serverIp, ftpPort);
			ftp.login(ftpUser, ftpPass);
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return "";
			}
			String s = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
			System.out.println(s);
			String uuid = UUID.randomUUID().toString().replace("-", "") + s;
			//上传文件到服务器
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
			ftp.enterLocalPassiveMode();
			ftp.storeFile(uuid, file.getInputStream());
			file.getInputStream().close();
			ftp.logout();
			url = path + uuid;
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftp.isConnected()) {
				ftp.disconnect();
			}
			return url;
		}
	}


}

